package com.gqr.lock.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 获取锁的过程中被中断
 */
public class LockInterruptibly implements Runnable {
    private Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        LockInterruptibly r = new LockInterruptibly();
        Thread t0 = new Thread(r);
        Thread t1 = new Thread(r);
        t0.start();
        t1.start();
        Thread.sleep(2000);
        // t0会打印睡眠期间被中断了
//        t0.interrupt();
        // t1 会打印获得锁期间被中断了
        t1.interrupt();
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "尝试获取锁");

        try{
            lock.lockInterruptibly();
            try{
                System.out.println(Thread.currentThread().getName()+"获取到了锁");
                Thread.sleep(5000);
            }catch (InterruptedException e){
                System.out.println(Thread.currentThread().getName()+"睡眠期间被中断了");
            } finally {
                lock.unlock();
                System.out.println(Thread.currentThread().getName()+"释放了锁");
            }

        }catch (InterruptedException e){
            System.out.println(Thread.currentThread().getName()+"获得锁期间被中断了");
        }
    }
}
